package com.xqboss.task.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xqboss.common.constant.CacheConstants;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.task.socket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

/**
 * websocket 消息监听
 */
@Service
@Slf4j
public class WsMsgListener implements MessageListener {

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            byte[] body = message.getBody();
            String data = RedisSerializer.string().deserialize(body);
            log.info("socket服务收到消息：{}", data);
            if (StringUtils.isNotEmpty(data)) {
                JSONObject json = JSON.parseObject(data);
                String userId = json.getString("userId");
                String msg = json.getString("msg");
                if (redisCache.getExpire(CacheConstants.KEY_USER_MSG_PUSH_CLOSE_TIME+userId) == -2) { // 为-2时，说明key不存在，说明用户没有暂时禁用消息推送
                    webSocketServer.sendOneMessage(userId, msg);
                }
            }
        } catch (Exception e) {
            log.error("推送失败!", e);
        }
    }
}
